package ltd.hxya.novel.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import ltd.hxya.novel.common.bean.BaseEntity;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.bean.ResultEnum;
import org.springframework.util.StringUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;

@Slf4j
public class BaseUtils {

    private Process process ;
    /**
     * 对于插入删除等操作，根据返回的条数，判断是否执行成功
     */
    public static Result hasRow(int row){
        return row>0?
                Result.success():
                Result.fail(ResultEnum.MYSQL_OPERATION_ERROR.getCode(), ResultEnum.MYSQL_OPERATION_ERROR.getMsg());
    }

    /**
     * 对于CreateTime和UpdateTime的时间校验进行封装
     */
    public static void compareTime(QueryWrapper queryWrapper, BaseEntity baseEntity){
        compareTime(queryWrapper,baseEntity,"create_time");
    }

    public static void compareTime(QueryWrapper queryWrapper,BaseEntity baseEntity,String column){
        Map<String, Object> params = baseEntity.getParams();
//            String beginTime = (String) params.get(ParamsConstant.BEGIN_TIME);
//            String endTime = (String) params.get(ParamsConstant.END_TIME);
            if (baseEntity.getBeginTime()!=null){
                queryWrapper.ge(column,baseEntity.getBeginTime());
            }
            if (baseEntity.getEndTime()!=null){
                queryWrapper.le(column,baseEntity.getEndTime());
            }
    }


    //返回操作类型
    public static Integer operType(String oper){
        switch (oper){
            case "新增": return 1;
            case "修改": return 2;
            case "删除": return 3;
            default: return 0;
        }
    }

    public static List<Object> getFieldValue(Object object) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        List<Object> fieldValues = new ArrayList<>();
        Field[] field = object.getClass().getDeclaredFields();        //获取实体类的所有属性，返回Field数组
        for(int j=0 ; j<field.length ; j++){     //遍历所有属性
            String fname = field[j].getName();    //获取属性名称

            System.out.println("attribute fname:"+fname);
            fname = fname.substring(0,1).toUpperCase()+fname.substring(1); //将属性的首字符大写，方便构造get，set方法
            String ftype = field[j].getGenericType().toString();    //获取属性的类型
            if(ftype.equals("class java.lang.String")){   //如果ftype是类类型，则前面包含"class "，后面跟类名
                Method m = object.getClass().getMethod("get"+fname);
                Object value =  m.invoke(object);    //利用反射原理，调用getter方法获取属性值
                if(value != null){
                    //对属性值的操作逻辑（如改变编码)
                    fieldValues.add(value);
                }
                if (value==null){
                    fieldValues.add(null);
                }
            }
        }
        return fieldValues;
    }

    public static void parseField(List<Object> fieldValues){
        String textValue = "";
        for (Object fieldValue : fieldValues) {
            textValue=textValue+",";
            if (fieldValue instanceof Boolean){
                textValue=textValue+" ";
            }

        }
    }

    //子那个定义获取所索引的列表遍历
    public static <E> void forEach(Iterable<? extends E> list, BiConsumer<Integer,? super E> action){
        Objects.requireNonNull(action);
        Objects.requireNonNull(list);
        Integer index = 0;
        for (E item : list) {
            action.accept(index,item);
            index++;
        }
    }

    public static String getUrl(String url,String baseUrl) {
        //判断该URL是否匹配网络地址
        //如果除了http部分还有//，则去除

        Matcher matcher = PatternUtils.pattern("[a-zA-z]+://[^\\s]*", url);
        if (matcher.find()){
            return url;
        }
        return baseUrl+url;
    }

    public static String[] structPythonParam(String ... params) {
        String exe = "python";
        String command = "D:\\Javastu\\project\\novel\\novel-common\\novel-utils\\src\\main\\java\\ltd\\hxya\\novel\\common\\script\\python\\crawl.py";
        List<String> cmdList = new ArrayList<>();
        cmdList.add(exe);
        cmdList.add(command);
        for (String param : params) {
            cmdList.add(param);
        }
        String[] cmdArray = cmdList.toArray(new String[cmdList.size()]);
        return cmdArray;
    }

    public static List<String> getCategory(String category) {
        String[] categorys = category.split(",");
        List<String> categoryList = new ArrayList<>();
        for (String s : categorys) {
            if (StringUtils.isEmpty(s)){
                continue;
            }
            categoryList.add(s);
        }
        return categoryList;
    }

    public static Integer getRandomId() {
        String timeId = IdWorker.getTimeId();
        Random random = new Random();
        int randomId = random.nextInt(1000000000);
        //int randomId = Integer.parseInt(timeId.substring(timeId.length() - 10, timeId.length() - 1)) + i;
        return randomId;
    }

    //对一个集合求它的最大值
    public Double maxValue(List<Double> list){
        Map<String,Double> maxMap = new HashMap<>();
        maxMap.put("max",0.00);
        list.forEach(item->{
            Double max = maxMap.get("max");
            if (item>max){
                maxMap.put("max",item);
            }
        });
        return maxMap.get("max");
    }

    public  BufferedReader execScript(String[] cmdArr) throws IOException {
         this.process= Runtime.getRuntime().exec(cmdArr);
         //输出错误信息
        InputStream inputStream = this.process.getInputStream();
        InputStream errorStream = this.process.getErrorStream();
        BufferedReader errorBufferReader = new BufferedReader(new InputStreamReader(errorStream));
        String message = "";
        /*while ((message=errorBufferReader.readLine())!=null){
            System.out.println(message);
        }*/

        InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        return bufferedReader;
    }

    public  int waitFor(String availableIp) throws InterruptedException {
        int flag = this.process.waitFor();
        if (flag==0){
            log.info("ip:"+availableIp+"访问成功");
        }else {
            log.error("ip:"+availableIp+"访问失败");
        }
        return flag;
    }

    public  Process getProcess(){
        return this.process;
    }


}
